import { handler, view, BondViewGroup, binder } from "bibl";
import MentalService from "./state.js";
import template from './template.html';
import style from './style.scss';
import { Record } from "../utils/Record.js";
import Scene from './scene/index.js';
import { NumUtils } from './../utils/NumUtils.js';
import Result from './result';
import correctIcon from './../base/icons/correct.icon';
import timeIcon from './../base/icons/time.icon';

@view({
    className: "src-mental",
    style,
    template,
    dataset: {
        service: MentalService
    }
})
class Mental extends BondViewGroup {
    onready() {
        this.record = new Record();
        this.record.start();
        this.getNextExp();
        this.timeUpdate();
    }

    tags() {
        return {
            'x-scene': Scene
        }
    }

    icons() {
        return [correctIcon,timeIcon];
    }

    onunload() {
        clearTimeout(this.timeRecord);
    }

    @binder("replay")
    onreplay(){
        this.record.reStart();
        this.getNextExp();
    }

    @binder('gotoWelcome')
    gotoWelcome(){
        this.dispatchEvent('gotoWelcome');
    }

    @handler('next')
    next({ data }) {
        this.record.selectEnd(data);
        if (this.record.size() == this.getCurrentState().size) {
            this.record.stop();
            this.commit('timeUpdate', this.record.getStatistic());
            clearTimeout(this.timeRecord);
            this.addChild(Result, {
                parameter: {
                    list: this.record.list,
                    statistic:this.record.getStatistic()
                }
            });
        } else {
            this.getNextExp();
        }
    }

    @handler("replay")
    replay(){
        this.record.reStart();
        this.getNextExp();
        this.removeChildByType(Result);
    }

    timeUpdate() {
        this.commit('timeUpdate', this.record.getStatistic()).then(() => {
            this.timeRecord = setTimeout(() => this.timeUpdate(), 1000);
        });
    }

    getNextExp() {
        let exp = NumUtils.getExp(2,this.getCurrentState().size2);
        let dots = exp.getList();
        let value = exp.getValue();
        let result = exp.getResult();
        this.record.startSelect({ dots, value });
        this.commit('next', {
            dots,
            result,
            statistic: this.record.getStatistic()
        });
    }
}

export default Mental;